/*
 * @Description:
 * @Author: maskMan
 * @LastEditTime: 2024-11-21 11:48:10
 */
import { VuexModule, Module, Mutation, Action, getModule } from 'vuex-module-decorators';
import { RouteConfig } from 'vue-router';
import { asyncRoutes, constantRoutes } from '@/router';
import store from '@/store';
import { ManagerModule } from './manager';
import { util } from '@/utils/util';
export const filterAsyncRoutes = (): RouteConfig[] => {
  const routeList: RouteConfig[] = [];
  const roles = ManagerModule.roles;
  const routes = util.clone(asyncRoutes);
  for (const key in roles) {
    for (let index = 0; index < routes.length; index++) {
      const item = routes[index];
      if (item.meta?.name == key) {
        const repeat = routeList.find((v) => v.meta?.name == key);
        if (!repeat) {
          routeList.push({ ...item });
        }
      }
    }
  }
  if (routes.length) {
    routeList.push(routes[routes.length - 1]);
  }
  return routeList;
};
export interface IPermissionState {
  routes: RouteConfig[];
  dynamicRoutes: RouteConfig[];
}
@Module({ dynamic: true, store, name: 'permission' })
class Permission extends VuexModule implements IPermissionState {
  public routes: RouteConfig[] = [];
  public dynamicRoutes: RouteConfig[] = [];
  @Mutation
  SET_ROUTES(routes: RouteConfig[]) {
    this.routes = constantRoutes.concat(routes);
    this.dynamicRoutes = routes;
  }
  @Action
  public GenerateRoutes() {
    let accessedRoutes = filterAsyncRoutes();
    this.SET_ROUTES(accessedRoutes);
  }
}
export const PermissionModule = getModule(Permission);
